import { NameSpace } from 'utils/index';
import { Message } from '@teamix/ui';
import utils from 'utils';
import exceed from 'utils/apimap';
import intl from '../../../../../../../locale';

const { pathResource } = window.FORCE;
const ns = NameSpace('projectBranch');

export const UPDATE_DATA = ns('UPDATE_DATA');
export const SET_TAB_KEY = ns('SET_TAB_KEY');
export const DELETE_BRANCH = ns('DELETE_BRANCH');
export const RECEIVE_BRANCH_DATA = ns('RECEIVE_BRANCH_DATA');
export const RECEIVE_OVERVIEW_DATA = ns('RECEIVE_OVERVIEW_DATA');
export const RESET_STATE = ns('RESET_STATE');

export function updateData(data) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data,
    });
  };
}

export function setTabKey(data) {
  return (dispatch) => {
    dispatch({
      type: SET_TAB_KEY,
      data,
    });
  };
}

export function getAllData(page, value, per_page) {
  // 目的是使2个请求都结束才设置loading状态
  return (dispatch, getState) => {
    dispatch({
      type: UPDATE_DATA,
      data: {
        isLoading: true,
      },
    });
    const state = getState().project.projectBranches;
    const { tabKey, pageSize = 10 } = state;
    const category = tabKey === 'overview' ? 'all' : tabKey;
    Promise.all([
      exceed.forceFetch({
        api: 'projects.overview.branches',
        params: {
          projectId: pathResource.id,
        },
      }),
      exceed.forceFetch({
        api: 'projects.branches.category',
        params: {
          projectId: pathResource.id,
          category,
        },

        data: {
          search: value,
          per_page: per_page || pageSize,
          page,
        },
      }),
    ]).then(([res1, res2]) => {
      dispatch({
        type: RECEIVE_OVERVIEW_DATA,
        data: res1,
      });
      const { defaultBranch } = window.FORCE.pathResource;
      const { list } = res2;
      if (defaultBranch) {
        let i;
        const res = [];
        for (i = 0; i < list.length; i += 1) {
          if (list[i].name === defaultBranch) {
            res.unshift(list[i]);
          } else {
            res.push(list[i]);
          }
        }
        res2.list = res;
      }
      dispatch({
        type: RECEIVE_BRANCH_DATA,
        data: Object.assign(res2, {
          currentPage: page,
        }),
      });
      dispatch({
        type: UPDATE_DATA,
        data: {
          isLoading: false,
        },
      });
    });
  };
}

export function getOverviewData() {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data: {
        isLoading: true,
      },
    });
    exceed
      .forceFetch({
        api: 'projects.overview.branches',
        params: {
          projectId: pathResource.id,
        },
      })
      .then((result) => {
        dispatch({
          type: RECEIVE_OVERVIEW_DATA,
          data: result,
        });
        dispatch({
          type: UPDATE_DATA,
          data: {
            isLoading: false,
          },
        });
      });
  };
}

export function getBranchData(page, value, per_page) {
  return (dispatch, getState) => {
    const state = getState().project.projectBranches;
    const { tabKey, pageSize = 10 } = state;
    const category = tabKey === 'overview' ? 'all' : tabKey;
    dispatch({
      type: UPDATE_DATA,
      data: {
        isLoading: true,
      },
    });
    exceed
      .forceFetch({
        api: 'projects.branches.category',
        params: {
          projectId: pathResource.id,
          category,
        },

        data: {
          search: value,
          per_page: per_page || pageSize,
          page,
        },
      })
      .then((result) => {
        const { defaultBranch } = window.FORCE.pathResource;
        const { list } = result;
        if (defaultBranch) {
          let i;
          const res = [];
          for (i = 0; i < list.length; i += 1) {
            if (list[i].name === defaultBranch) {
              res.unshift(list[i]);
            } else {
              res.push(list[i]);
            }
          }
          result.list = res;
        }
        dispatch({
          type: RECEIVE_BRANCH_DATA,
          data: Object.assign(result, {
            currentPage: page,
          }),
        });
        dispatch({
          type: UPDATE_DATA,
          data: {
            isLoading: false,
          },
        });
      });
  };
}

export function deleteBranch(branch, cbSucc, cbErr) {
  return (dispatch, getState) => {
    const state = getState().project.projectBranches;
    const { tabKey } = state;
    exceed
      .fetch({
        api: 'project.branches.delete',
        params: {
          projectId: pathResource.id,
          branch: utils.revisionEncodeURI(branch),
        },
      })
      .then(() => {
        Message.success({
          title: intl.get({
            id: 'code-assets.projectBranches.actions.BranchDeleted',
            defaultMessage: '分支删除成功',
          }),
        });

        if (tabKey === 'overview') {
          dispatch(getAllData(1));
        } else {
          dispatch(getBranchData(1));
        }
        cbSucc && cbSucc();
      })
      .fail(() => {
        cbErr && cbErr();
      });
  };
}

export function resetState() {
  return (dispatch) => {
    dispatch({
      type: RESET_STATE,
    });
  };
}
